<?php

namespace App\Http\Controllers\Admin;

use App\Exports\ProductExport;
use App\Http\Requests\Admin\ProductRequest;
use App\Models\Brand;
use App\Models\Product;
use App\Models\User;
use Carbon\Carbon;
use Chumper\Zipper\Facades\Zipper;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class ProductsController extends Controller
{
    public function index(Product $product, ProductRequest $request)
    {
        $query = $product->query();
        if ($request->has('brand_id')) {
            $query = $query->where('brand_id', $request->input('brand_id'));
        }
        $products = $query->with('brand')->orderBy('sort', 'desc')->paginate(20);

        return $this->success($products);
    }
    
    public function store(ProductRequest $request, Product $product)
    {
        $product->fill($request->all());
        $product->save();

        return $this->message('添加成功');
    }

    public function update(Product $product, ProductRequest $request)
    {
        $product->update($request->all());
        return $this->message('更新成功');
    }

    /**
     * @param Product $product
     * @return mixed
     */
    public function show(Product $product)
    {
        return $this->success($product);
    }

    public function destroy(Product $product)
    {
        // 删除照片
        $image = DB::table('products')->where('id', $product->id)->value('image');
        $res = Storage::disk('oss')->delete($image);
        $product->delete();

        return $this->message($res);
    }

    public function export()
    {
        return Excel::download(new ProductExport, 'products.xlsx');
    }

    /**
     * @param ProductRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bulkImport(Request $request)
    {
        $this->validate($request, [
            'products' => 'required|file',
        ]);
        $path = $request->file('products')->store('zip', 'local');

        // 解压至本地
        Zipper::make(storage_path('app/') . $path)->extractTo(storage_path('app/public'));

        // 遍历本地文件
        $this->traverse(storage_path('app/public'));

        // 删除压缩包
        sleep(1);
        unlink(storage_path('app/') . $path);

        return response()->json([
            'code' => 200,
            'message' => '导入成功',
        ]);
    }

    /**
     * @param $path
     */
    protected function traverse($path)
    {
        $currentDir = opendir($path);
        $product = [];
        $now = Carbon::now()->toDateTimeString();
        while (($file = readdir($currentDir)) !== false) {
            $subDir = storage_path('app/public') . DIRECTORY_SEPARATOR . $file;
            if ($file == '.' || $file == '..' || $file == '.gitignore') {
                continue;
            } else if (is_dir($subDir)) {
                self::traverse($subDir);
                rmdir($subDir);
            } else {
                // 读取文件名并上传
                $filePath = $path . DIRECTORY_SEPARATOR . $file;
                $filename = pathinfo($filePath, PATHINFO_FILENAME);
                $fileFullName = pathinfo($filePath, PATHINFO_BASENAME);

                // 跳过命名无效的文件
                if (strpos($filename, '-') === false) {
                    unlink($filePath);
                    continue;
                } else if (strpos(strtoupper($filename), 'SK-II') !== false && substr_count($filename, '-') < 2) {
                    unlink($filePath);
                    continue;
                }

                // 获取文件名
                if (strpos(strtoupper($filename), 'SK-II') !== false) {
                    $brandName = 'SK-II';
                    list(,, $productName) = explode('-', $filename);
                } else {
                    list($brandName, $productName) = explode('-', $filename);
                }
                list($width, $height) = getimagesize($filePath);

                // 查询品牌是否创建
                $brand = Brand::query()->where('name', $brandName)->first();
                if (!$brand) {
                    $brand = new Brand();
                    $brand->name = $brandName;
                    $brand->save();
                }
                // 判断商品是否存在
                $existProduct = Product::query()->where('brand_id', $brand->id)->where('name', $productName)->first();
                if ($existProduct) {
                    unlink($filePath);
                    continue;
                }

                // 上传到腾讯云
                $storage = Storage::disk('oss');
                $storage->putFileAs('images', new UploadedFile($filePath, $fileFullName), $fileFullName);

                $product[] = [
                    'brand_id' => $brand->id,
                    'name' => $productName,
                    'image' => 'images/' . $fileFullName,
                    'image_width' => $width,
                    'image_height' => $height,
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
                unlink($filePath);
            }
        }
        Product::insert($product);
    }
}
